<template>
  <div>
    <bpm-c-subtitle :title="subTitle"
                    :isCollapse="false">
      <bpm-d-grid v-loading="showLoading"
                  :note="gridNote"
                  ref="paymentallgrid"
                  :showArray="showArray"
                  head="payment"
                  :writeAble="writeAble"
                  :showExtraStyle="true"
                  :showCheckbox="true"
                  :gridInfo="gridInfo"
                  :gridTypeInfo="gridTypeInfo"
                  :gridTitleInfo="gridTitleInfo"
                  :gridShowInfo="gridShowInfo"
                  :gridEditInfo="gridEditInfo"
                  :gridWidthInfo="gridWidthInfo"
                  :pageMax="pageMax"
                  :pageStart="pageStart"
                  :pageCount="pageCount"
                  :validateExp="validateExp"
                  @addClicked="addClicked"
                  @updateClicked="updateClicked"
                  @deleteClicked="deleteClicked"
                  @gridClicked="gridClicked"
                  @gridDBLClicked="gridDBLClicked"
                  @gridCheckedChanged="gridCheckedChanged"
                  @gridStatusChanged="gridStatusChanged"
                  @gridPageChanged="gridPageChanged"
                  @gridCellEditEnd="gridCellEditEnd"
                  @saveClicked="saveClicked"/>
      <bpm-d-paymentgrid class="content"
                         :showExtraStyle="true"
                         v-if="showChailvPart" />
    </bpm-c-subtitle>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
// import JsReimburseDraft from '../../../../js/business/SSCV3/Reimburse/SSCV3.Reimburse_Draft'

export default {
  name: 'bpmDPaymentarea',
  data () {
    return {
      validateExp: {
        2: {
          flag: true,
          maxlength: 14,
          require: true,
          positiveDecimal: true
        },
        3: {
          flag: true,
          maxlength: 14,
          positiveDecimal: true
        }
      },
      gridStatus: '',
      gridSelectIndex: '',
      gridShowInfo: [
        'internalordername',
        'subjectname',
        'notincludetaxessum',
        'taxrate',
        'reimbursesum',
        'actualreimbursesum',
        'summary'
      ],
      gridWidthInfo: [120, 120, 100, 100, 100, 100, 300], // 保证总和为980，如果有复选框则总和为940
      gridTypeInfo: [
        'text',
        'text',
        'number',
        'number',
        'number',
        'number',
        'text'
      ],
      gridLoading: false
    }
  },
  computed: {
    ...mapState(['pageType', 'tsPiid', 'ssc', 'pageType', 'pageTypeEnum', 'gridPageInfo', 'lang', 'otherI18n', 'dialogloading']),
    showLoading () {
      return this.gridLoading || (this.dialogloading !== 0)
    },
    gridEditInfo () {
      if (this.pageType === this.pageTypeEnum.approveFee) {
        return [
          'notincludetaxessum',
          'taxrate'
        ]
      }
      return []
    },
    subTitle () {
      return this.getLanguage('title.reimDetails')
    },
    gridTitleInfo () {
      return [
        this.getLanguage('label.innerOrder'),
        this.getLanguage('label.costShareSubject'),
        this.getLanguage('label.whBtReimburseDdSub.notincludetaxessum'),
        this.getLanguage('label.whBtReimburseDdSub.taxrate'),
        this.getLanguage('label.whBtReimburseDdSub.reimbursesum'),
        this.getLanguage('label.whBtReimburseDdSub.actualreimbursesum'),
        this.getLanguage('label.whBtReimburseDdSub.summary')
      ]
    },
    gridNote () {
      if (this.pageType === this.pageTypeEnum.draft) {
        if (this.gridStatus === 'update') {
          return this.otherI18n.updateWarn
        } else {
          return this.otherI18n.dbclkNote
        }
      }
      if (this.pageType === this.pageTypeEnum.approveFee) {
        return ''
      }
      return ''
    }, // this.getLanguage('alert.sjxzxgjl'),
    pageMax () {
      return this.gridPageInfo.ssc.reimburse.whBtReimburseDdSub.max
    },
    pageStart () {
      return this.gridPageInfo.ssc.reimburse.whBtReimburseDdSub.start
    },
    pageCount () {
      return this.gridPageInfo.ssc.reimburse.whBtReimburseDdSub.count
    },
    writeAble () {
      if (this.pageType === this.pageTypeEnum.view || this.pageType === this.pageTypeEnum.approve) {
        return false
      }
      return true
    },
    showArray () {
      if (this.pageType === this.pageTypeEnum.draft) {
        return ['add', 'delete']
      }
      if (this.pageType === this.pageTypeEnum.approveFee) {
        return []
      }
      return []
    },
    gridInfo: {
      get () {
        console.log('--------ssss', this.ssc.reimburse.whBtReimburseDdSub)
        return this.ssc.reimburse.whBtReimburseDdSub
      },
      set (value) {
        this.$store.commit('SetDataSscReimburseWhBtReimburseDdSub', value)
      }
    },
    chailvRowGridInfo () {
      console.log('chailvrow payment grid item', this.$store.state.chailvRow.ssc.reimburse.whBtReimburseDdSub)
      return this.$store.state.chailvRow.ssc.reimburse.whBtReimburseDdSub
    },
    showChailvPart () {
      // return true
      if (this.pageType === this.pageTypeEnum.draft) {
        return false
      } else {
        console.log('chailvROW', this.chailvRowGridInfo)
        return (this.chailvRowGridInfo && this.chailvRowGridInfo.tsId)
      }
    }
  },
  methods: {
    ...mapActions(['getDataFromTableCostshare', 'AJAX_Reim_011_Draft_SaveData', 'AJAX_Reim_021_ApproveFee_SaveData',
      'getDataFromTableDdSub', 'queryBudgetSubject', 'queryInternalOrder',
      'updateTableWh_bt_reimburse_dd_sub', 'checkBeforeSaveForDraft', 'CheckSubjectExists', 'AJAX_Reim_020_DraftDel_MultiData'
    ]),
    ...mapActions(['resetGridSelectRowWhBtReimburseDdSub', 'resetGridSelectRowWhBtFareDetails', 'resetGridSelectRowWhBtStayDetails']),
    ...mapActions(['resetGridSelectRowWhBtTravelSubsidyDetails', 'resetGridSelectRowWhBtTransportationDetails', 'callTotalMoney']),
    ...mapActions(['initWhBtFaredetails', 'initWhBtStaydetails', 'initWhBtTravelsubsidydetails', 'getbxmxMidFromDb', 'updateCardMakingSumByMid4Vue']),
    ...mapActions(['getDataSscReimburseFromMoreTable']),
    updateClicked () {},
    addClicked () {
      // 为什么要在新增时，查询mid，只能在添加差旅费时使用。目前组件在差旅费弹窗页面无法触发add方法。marked by gyren
      // 注意：这里不能做异步查找，后续根据同步结果判断是否要生成新的MID  marked by gyren
      this.getbxmxMidFromDb({
        me: this,
        async: false
      })
      this.gridLoading = true
      setTimeout(() => {
        // 获取内部订单数组
        let param = {}
        param.me = this
        param.queryInternalOrderCode = ''
        param.queryInternalOrderName = ''
        param.companyCode = this.ssc.reimburse.whBtReimburse.reimbursecompanycode
        param.costcenterCode = this.ssc.reimburse.whBtReimburse.reimbursecostcentercode
        param.async = true
        this.queryInternalOrder(param)
        this.gridLoading = false
      }, 100)
      // 起草
      if (this.$store.state.bxmxGradState === 'add') {
        if (this.$store.state.bxmxMid === 'NONE') {
          this.$store.state.bxmxMid = 'MID-' + this.getUuid()
        }
        this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub.mid = this.$store.state.bxmxMid
        this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub.tsId = this.$store.state.tsId
      } else {
        this.$store.state.bxmxMid = this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub.mid
      }
      // $CV('local.mid').val(this.$store.state.bxmxMid)
      console.log('起草的差旅的报销明细的选中mid', this.$store.state.bxmxMid)
      console.log('起草的差旅的报销明细的选中Rowmid', this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub.mid)
    },
    deleteClicked () {
      if (this.pageType === this.pageTypeEnum.draft) {
        // 删本父表
        console.log('============', this.$store.state.bxmcCheckedMids)
        this.httpBpmDelBz({
          mids: this.$store.state.bxmcCheckedMids.split(','),
          tableName: 'wh_bt_reimburse_dd_sub'
        })
        // 调用020,批量删除数据
        this.AJAX_Reim_020_DraftDel_MultiData({
          me: this,
          mids: this.$store.state.bxmcCheckedMids
        })
        if (this.$store.state.retMsg !== '') {
          this.alert(this.getResource('alert.information.delerror'))
          return
        }
        // 刷新本父表,删除时可能删除的是差旅费，所以要再次加载孙子表给数据中心  gyren marked
        // this.getDataFromTableDdSub({me: this, async: true})
        // this.getDataFromTableCostshare({me: this, async: true})
        let paramJson = {}
        paramJson.me = this
        // paramJson.tableNames = 'wh_bt_reimburse,wh_bt_reimburse_dd_sub,wh_bt_reimburse_costshare,wh_bt_travelsubsidydetails,wh_bt_transportationdetails,wh_bt_faredetails,wh_bt_staydetails,wh_bt_reimburse_rcm_details,wh_bt_reimburse_rcm_sub'
        paramJson.tableNames = 'WH_BT_TRAVELSUBSIDYDETAILS,WH_BT_FAREDETAILS,WH_BT_STAYDETAILS,WH_BT_REIMBURSE_COSTSHARE,WH_BT_REIMBURSE_DD_SUB'
        paramJson.BB = 'N'
        this.getDataSscReimburseFromMoreTable(paramJson)
        // 计算可冲抵金额
        this.calculateAfter()
        // console.log('deleted==========================', this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub)
        // let ddsubItem = this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub
        // if (ddsubItem.subjectcode === '500307000101' || ddsubItem.subjectcode === '500307000901') {
        //   // 清除子表数据
        //   this.resetGridSelectRowWhBtFareDetails({me: this})
        //   this.resetGridSelectRowWhBtStayDetails({me: this})
        //   this.resetGridSelectRowWhBtTravelSubsidyDetails({me: this})
        //   this.resetGridSelectRowWhBtTransportationDetails({me: this})
        //   this.initWhBtFaredetails({me: this})
        //   this.initWhBtStaydetails({me: this})
        //   this.initWhBtTravelsubsidydetails({me: this})
        // }
        // this.resetGridSelectRowWhBtReimburseDdSub({me: this})
      }
    },
    saveClicked () {
      let saveFlag = 'update'
      if (this.pageType === this.pageTypeEnum.approveFee) {
        // 刷新费用报销grid数据；在原js里的onEditCell方法里下面方法被屏蔽了，因为线上是行编辑，所以不需要刷新
        if (!this.onEditCell()) {
          return false
        }
        let dbSubobj = this.$store.state.gridSelectRow.ssc.reimburse
          .whBtReimburseDdSub
        console.log('**************###############***********')
        this.updateTableWh_bt_reimburse_dd_sub({
          me: this,
          data: {
            mid: dbSubobj.mid,
            taxrate: dbSubobj.taxrate,
            notincludetaxessum: dbSubobj.notincludetaxessum,
            actualreimbursesum: dbSubobj.actualreimbursesum
          }
        })
        // 平衡各表之间数据
        this.AJAX_Reim_021_ApproveFee_SaveData({
          me: this,
          data: this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub
        })
        // 检查失败，则不再执行；
        if (this.$store.state.returnCode !== '000000') {
          this.alert(this.getResource(this.$store.state.retMsg))
          this.$store.state.returnCode = '000000'
          this.$store.state.retMsg = ''
          return false
        }
        let paramJson = {}
        paramJson.me = this
        // paramJson.tableNames = 'wh_bt_reimburse,wh_bt_reimburse_dd_sub,wh_bt_reimburse_costshare,wh_bt_travelsubsidydetails,wh_bt_transportationdetails,wh_bt_faredetails,wh_bt_staydetails,wh_bt_reimburse_rcm_details,wh_bt_reimburse_rcm_sub'
        paramJson.tableNames = 'WH_BT_TRAVELSUBSIDYDETAILS,WH_BT_FAREDETAILS,WH_BT_STAYDETAILS,WH_VBT_REIMBURSE_RCM_DETAILS,WH_BT_REIMBURSE_COSTSHARE,WH_BT_REIMBURSE_DD_SUB'
        paramJson.BB = 'N'
        this.getDataSscReimburseFromMoreTable(paramJson)
        // 计算可冲抵金额
        this.reloadRechargeMoney()
        return true
      } else if (this.pageType === this.pageTypeEnum.draft) {
        if (this.gridStatus === 'add') {
          saveFlag = ''
        }
        let result = this.checkBeforeSave()
        // let obj = this.checkBeforeSaveForDraft()
        if (!result) {
          return
        }
        let taxrate = this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub.taxrate
        if (taxrate === null || taxrate === '' || taxrate === 0) {
          this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub.taxrate = '0'
        }
        let dbSubobj = this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub
        dbSubobj.tsId = this.$store.state.tsId
        if (this.$store.state.bxmxGradState === 'add') {
          dbSubobj.mid = 'MID-' + this.getUuid() // uuid
          this.CheckSubjectExists({
            me: this,
            data: this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub
          })
          if (this.$store.state.ssc.reimburse.checkExistResult > 0) {
            // this.alert('同级报销订单中，相同的科目只允许报销一次，请修改')
            this.alert(this.getResource('alert.information.tjbxdkmxz'))
            return
          }
        }
        this.updateTableWh_bt_reimburse_dd_sub({
          saveFlag: saveFlag,
          me: this,
          data: dbSubobj
        })
        this.AJAX_Reim_011_Draft_SaveData({
          me: this,
          fatherOrChild: 'father',
          data: this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub
        })
        // JsReimburseDraft.statAllDetail()
        // this.getDataFromTableDdSub({me: this, async: true})
        // this.getDataFromTableCostshare({me: this, async: true})
        let paramJson = {}
        paramJson.me = this
        // paramJson.tableNames = 'wh_bt_reimburse,wh_bt_reimburse_dd_sub,wh_bt_reimburse_costshare,wh_bt_travelsubsidydetails,wh_bt_transportationdetails,wh_bt_faredetails,wh_bt_staydetails,wh_bt_reimburse_rcm_details,wh_bt_reimburse_rcm_sub'
        paramJson.tableNames = 'WH_BT_REIMBURSE_COSTSHARE,WH_BT_REIMBURSE_DD_SUB'
        paramJson.BB = 'N'
        this.getDataSscReimburseFromMoreTable(paramJson)
        // 计算可冲抵金额
        this.calculateAfter()
      }
      // mmsuna hide
      this.$refs.paymentallgrid.hideGridHead(true)
    },
    gridClicked (index, item) {
      this.gridSelectIndex = index
      this.$store.state.gridSelectIndex.whBtReimburseDdSub = index
      // 原setChildMidValue的实现
      // var travelArea = item.travelarea // 出差地区列
      // var selectSubject = item.subjectcode // 科目代码列
      // travelArea = JS_Reimburse_ApproveFee.chgTravelArea(travelArea)
      // $CV('local.travelarea').val(travelArea)
      // $CV('local.selectSubject').val(selectSubject)
      // -----------------------给mid赋值,每个点击事件都要做
      // $CV('local.mid').val(item.mid)
      this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub = item
    },
    gridDBLClicked (index, item) {
      // if (this.pageType === this.pageTypeEnum.draft) {
      //   if (!JsReimburseDraft.setOpenUrlParameter()) {
      //     return
      //   }
      //   JsReimburseDraft.getOrderInfo()
      // }
      this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub = item
      this.$store.state.bxmxMid = item.mid
      if (this.pageType !== this.pageTypeEnum.draft) {
        return
      }
      this.gridLoading = true
      setTimeout(() => {
        // 获取内部订单数组
        let param = {}
        param.me = this
        param.queryInternalOrderCode = ''
        param.queryInternalOrderName = ''
        param.companyCode = this.ssc.reimburse.whBtReimburse.reimbursecompanycode
        param.costcenterCode = this.ssc.reimburse.whBtReimburse.reimbursecostcentercode
        param.async = true
        this.queryInternalOrder(param)
        if (item && item.internalordercode) {
          let param2 = {}
          param2.me = this
          param2.companyCode = this.ssc.reimburse.whBtReimburse.reimbursecompanycode
          param2.costingCenterCode = this.ssc.reimburse.whBtReimburse.reimbursecostcentercode
          param2.inwardOrderCode = item.internalordercode
          param2.budgetSubjectName = ''
          param2.budgetSubjectCode = ''
          param2.flag = 'pay'
          param2.async = true
          this.queryBudgetSubject(param2)
        }
        // this.$store.state.gridDBLClicked.whBtReimburseDdSub = true
        this.gridLoading = false
      }, 100)
    },
    setDialogClose () {},
    gridCheckedChanged (v) {
      let strs = ''
      for (var i = 0; i < v.length; i++) {
        strs += this.$store.state.ssc.reimburse.whBtReimburseDdSub[v[i]].mid + ','
      }
      if (strs !== '') {
        strs = strs.substring(0, strs.length - 1)
      }
      this.$store.state.bxmcCheckedMids = strs
    },
    gridStatusChanged (v) {
      this.gridStatus = v
      this.$store.state.bxmxGradState = v
    },
    gridPageChanged (v) {
      console.log('payment', v)
      if (v.name === 'count' || v.name === 'start') {
        let json = {
          path: 'whBtReimburseDdSub',
          name: v.name,
          value: v.value
        }
        this.$store.commit('upGridPageInfoWithPathAndValue', json)
        let json2 = {
          async: true,
          me: this
        }
        this.getDataFromTableDdSub(json2)
      }
    },
    gridCellEditEnd: function (record, recordFieldValue) {
      // this.$emit('gridCellEditEnd', record, recordFieldValue)
      this.gridLoading = true
      setTimeout(() => {
        this.$store.state.gridSelectRow.ssc.reimburse.whBtReimburseDdSub = record
        if (!this.saveClicked()) {
          this.getDataFromTableDdSub({me: this, async: true})
        } else {
          this.tips(this.getResource('alert.tips.sjxgcg'))
        }
        this.gridLoading = false
      }, 100)
    }

  }// ,
  // created () {
  //   console.log('页面类型', this.pageType)
  //   // if (this.pageType === this.pageTypeEnum.draft) {
  //   // setTimeout(() => {
  //   /* JsReimburseDraft.setInitPage() */
  //   console.log('yemian down.....')
  //   let json = {
  //     async: true,
  //     me: this,
  //     succfunc: function () {
  //       JsReimburseDraft.amountReimSum(null, 'datas')
  //     }
  //   }
  //   console.log('yemian up.....')
  //   this.getDataFromTableDdSub(json)
  //   // }, 500)
  //
  //   /* } else {
  //   } */
  // }
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .content {
    width: 100%;
    display: block;
  }
</style>
